﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LibCommon;
using RTCCore;

namespace LibRTC.Core.MessageMap {
    /// <summary>
    /// This class is used to deal with all the RTC Event
    /// </summary>
    public class RTCMessageMap
    {
        // Logger class
        private static ILogger LOGGER = LoggerFactory.GetLogger("RTCMessageMap", null);

        private readonly Dictionary<RTC_EVENT,IMessageHandler> _eventHandlerMap = new Dictionary<RTC_EVENT, IMessageHandler>();

        // make this class as a singleton
        private static RTCMessageMap _instance = null;

        private RTCMessageMap()
        {
        }

        /// <summary>
        /// Get the instance of this class, we make this class singleton
        /// </summary>
        /// <returns>instance of RTCMessageMap</returns>
        public static RTCMessageMap GetInstance()
        {
            if(null == _instance)
            {
                _instance = new RTCMessageMap();
            }

            return _instance;
        }

        /// <summary>
        /// Register Event Handler 
        /// </summary>
        /// <param name="rtcEvent">event type</param>
        /// <param name="handler">event handler</param>
        public void RegisterEventHandler(RTC_EVENT rtcEvent, IMessageHandler handler) {
            if(!_eventHandlerMap.ContainsKey(rtcEvent)) {
                _eventHandlerMap.Add(rtcEvent, new MessagePipline(rtcEvent,"MessagePipeline:"+rtcEvent));
            }

            IMessageHandler pipelineHandler;

            _eventHandlerMap.TryGetValue(rtcEvent, out pipelineHandler);

            Debug.Assert(null != pipelineHandler);

            LOGGER.LogInfo("Register Event Handler "+rtcEvent + " "+handler.Name());

            pipelineHandler.RegisterHandler(handler);
        }

        /// <summary>
        /// Entry for Event processing
        /// </summary>
        /// <param name="rtcEventType">event type</param>
        /// <param name="rtcEvent">event object</param>
        public void OnRTCEvent(RTC_EVENT rtcEventType, object rtcEvent)
        {
            LOGGER.LogDebug("Entering RTCMessageMap.OnRTCEvent " + rtcEventType);

            // lookup map and process event
            if(_eventHandlerMap.ContainsKey(rtcEventType)) {
                IMessageHandler handler;
                _eventHandlerMap.TryGetValue(rtcEventType, out handler);
                Debug.Assert(null != handler);
                handler.Process(rtcEventType,rtcEvent);
            }
        }
    }
}